package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author Suave
 * @date 2024/8/16
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理订单超时
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrders() {
        log.info("处理超时订单");
//        获取当前时间十五分钟前的时间
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
//        获取待付款并且超时的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);

//        修改订单状态和设置时间、原因
        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.stream().forEach(orders -> {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason("订单超时未付款");
                orderMapper.update(orders);
            });
        }
    }

    /**
     * 处理完成但未点击完成订单订单
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrders(){
        log.info("处理用户为点击完成的订单");
//        获取当天零点的时间
        LocalDateTime time = LocalDateTime.now().plusHours(-1);

//        获取前一天派送中的订单
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);

//        将派送中的订单完成
        if(ordersList != null && !ordersList.isEmpty()){
            ordersList.stream().forEach(orders -> {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            });
        }
    }
}
